package xtreamclient

import com.eeeeeric.mpc.hc.api.FileInfo
import com.eeeeeric.mpc.hc.api.MediaPlayerClassicHomeCinema
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.BufferedInputStream
import java.io.IOException
import java.io.RandomAccessFile
import java.lang.Exception
import java.io.ByteArrayOutputStream



class MPVHandler() : VLCHandler {
    override var process: Process? = null

    var pipe:RandomAccessFile? = null
    override fun connect() {
        startMPV()
        Thread.sleep(1000)
        startPipe()
        GlobalScope.launch{
            printLogs()
        }
    }

    private fun startPipe() {
        try {
            pipe = RandomAccessFile("\\\\.\\pipe\\mpvsocket", "rw")
        } catch (e: Exception) {

        }
    }

    override fun playItem(streamURL: String, streamName: String) {
        val echoText = "{ \"command\": [\"loadfile\", \"${streamURL}\"], \"request_id\": 100 }\n"
        if (pipe==null) {
            startPipe()
        }
        try {
            pipe?.write(echoText.toByteArray())
        } catch (e:Exception) {
            startMPV()
            startPipe()
            Thread.sleep(500)
            playItem(streamURL,streamName)
        }
    }

    fun startMPV() {
        val rt = Runtime.getRuntime()
        process = rt.exec("\"F:\\PilotPrograms\\mpv\\mpv\" --input-ipc-server=\\\\.\\pipe\\mpvsocket --idle=yes nothing.mp3")
        //println(process?.inputStream?.readAllBytes().toString())
    }





}